package com.frame.web;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.frame.Result;
import com.frame.domain.Menu;
import com.frame.service.MenuService;
import com.mini.core.utils.StrKit;

/**
 * @author sxjun1904
 * @since 2016-8-8
 */
@Controller
public class IndexController extends BaseController{

    private static final Logger log = LoggerFactory.
            getLogger(IndexController.class);
    
    @Autowired
    private MenuService menuService;

    /**
     * 登录界面
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = {"/login","","/"}, method = RequestMethod.GET)
    public String login(Model model) {
        return "login";
    }

    /**
     * 登录认证
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "/auth", method = RequestMethod.POST)
    @ResponseBody
    public Result authenticate(String username,String password,HttpSession session) {
    	 UsernamePasswordToken credentials = new UsernamePasswordToken(username, password);
        log.info("Authenticating {}", credentials.getUsername());
        final Subject subject = SecurityUtils.getSubject();
        try {
			subject.login(credentials);
		} catch (AuthenticationException e) {
			e.printStackTrace();
            return error().setMsg("账号或者密码错误");
		}
        // set attribute that will allow session querying
        session.setAttribute("email", credentials.getUsername());
        return success();
    }
    
    /**
     * 退出
     * @return
     */
    @RequestMapping("logout")
	public String logout(){
		SecurityUtils.getSubject().logout();
		return "login";
	}
    
    /**
     * 主界面
     * @return
     */
    @RequestMapping(value = "/index")
    public String index(Model model,HttpSession session){
    	List<Menu> menus = menuService.findMenuByEmail((String)session.getAttribute("email"));
    	model.addAttribute("menus", menus);
    	return "index";
    }
    
    /**
     * 首页
     * @return
     */
    @RequestMapping(value = "/dashboard")
    public String dashboard(){
    	return "dashboard";
    }
    
}
